<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>注册</title>
    <link
      href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.0.2/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </head>
  <body>
    <div class="container">
      <legend>注册</legend>
      <div class="form-group">
        <label for="">用户名</label>
        <input
          type="text"
          class="form-control"
          id="username"
          placeholder="请输入用户名"
        />
      </div>
      <div class="form-group">
        <label for="">密码</label>
        <input
          type="text"
          class="form-control"
          id="password"
          placeholder="请输入密码"
        />
      </div>
      <button type="submit" class="btn btn-primary">注册</button>
      <a href="/login" class="btn btn-success">已有账号，去登录</a>
    </div>
    <script>
      $("button").click(function () {
        //获取输入框里的元素
        let username = $("#username").val();
        let password = $("#password").val();

        // 验证用户是否存在;
        $.ajax({
          url: "/isRegister",
          type: "post",
          data: {
            username: username,
          },
          success: function (res) {
            console.log(res);
            //如果可以注册，就执行可以注册的API
            if (res.code == 200) {
              $.ajax({
                url: "/doRegister",
                type: "post",
                data: {
                  username: username,
                  password: password,
                },
                success: function (res) {
                  console.log(res);
                  alert(res.msg);
                  if (res.code == 200) {
                    location.href = "/login";
                  }
                },
              });
            } else {
              alert(res.msg);
              location.reload();
            }
          },
        });

        // $.ajax({
        //   url: "/doregister",
        //   type: "post",
        //   data: {
        //     username: username,
        //     password: password,
        //   },
        //   success: function (res) {
        //     console.log(res);
        //   },
        // });
      });
    </script>
  </body>
</html>
